package com.demo.ctf;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ExceptionallyDemo {
    public static void main(String[] args) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            throw new RuntimeException("异步任务失败");
        });

        CompletableFuture<String> exceptionalFuture = future.exceptionally(throwable -> {
            // 处理异常，返回一个新的结果或抛出新的异常
            System.err.println("捕获到异常: " + throwable.getMessage());
            return "回退结果";
        });

        try {
            String result = exceptionalFuture.get();
            System.out.println("最终结果是: " + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}